from flask import request, jsonify, current_app
from flask_login import login_user, logout_user, login_required, current_user
from app import db, login_manager # Import from top-level app package
from app.models import User
from app.auth import bp
from app.utils.helpers import validate_captcha

@login_manager.user_loader
def load_user(user_id):
    return User.query.get(int(user_id))

@bp.route('/register', methods=['POST'])
def register():
    data = request.get_json()
    email = data.get('email')
    phone_number = data.get('phone_number')
    password = data.get('password')

    if not (email or phone_number) or not password:
        return jsonify({'error': 'Email or phone number and password are required'}), 400

    if email and User.query.filter_by(email=email).first():
        return jsonify({'error': 'Email already exists'}), 409

    if phone_number and User.query.filter_by(phone_number=phone_number).first():
        return jsonify({'error': 'Phone number already exists'}), 409

    user = User(email=email, phone_number=phone_number)
    user.set_password(password)
    db.session.add(user)
    db.session.commit()
    
    return jsonify({
        'message': 'User registered successfully',
        'user': {
            'id': user.id,
            'email': user.email,
            'phone_number': user.phone_number
        }
    }), 201

@bp.route('/login/password', methods=['POST'])
def login_password():
    data = request.get_json()
    identifier = data.get('identifier')
    password = data.get('password')

    if not identifier or not password:
        return jsonify({'error': 'Identifier and password are required'}), 400

    user = User.query.filter((User.email == identifier) | (User.phone_number == identifier)).first()

    if user and user.check_password(password):
        login_user(user, remember=data.get('remember_me', False))
        return jsonify({
            'message': 'Login successful',
            'user': {
                'id': user.id,
                'email': user.email,
                'phone_number': user.phone_number,
                'is_admin': user.is_admin
            }
        }), 200
    
    return jsonify({'error': 'Invalid identifier or password'}), 401

@bp.route('/login/phone/send-otp', methods=['POST'])
def send_otp():
    data = request.get_json()
    phone_number = data.get('phone_number')

    if not phone_number:
        return jsonify({'error': 'Phone number is required'}), 400

    # TODO: Implement OTP sending logic
    # Generate OTP, store hash, send via SMS service
    return jsonify({'message': 'OTP sent successfully'}), 200

@bp.route('/login/phone/verify-otp', methods=['POST'])
def verify_otp():
    data = request.get_json()
    phone_number = data.get('phone_number')
    otp = data.get('otp')

    if not phone_number or not otp:
        return jsonify({'error': 'Phone number and OTP are required'}), 400

    # TODO: Implement OTP verification logic
    # Verify OTP, create user if not exists, login user
    user = User.query.filter_by(phone_number=phone_number).first()
    if not user:
        user = User(phone_number=phone_number)
        db.session.add(user)
        db.session.commit()

    login_user(user)
    return jsonify({
        'message': 'Login successful',
        'user': {
            'id': user.id,
            'phone_number': user.phone_number
        }
    }), 200

@bp.route('/logout', methods=['POST'])
@login_required
def logout():
    logout_user()
    return jsonify({'message': 'Logged out successfully'}), 200

@bp.route('/me', methods=['GET'])
@login_required
def get_current_user():
    return jsonify({
        'user': {
            'id': current_user.id,
            'email': current_user.email,
            'phone_number': current_user.phone_number,
            'email_verified': current_user.email_verified,
            'phone_verified': current_user.phone_verified,
            'is_admin': current_user.is_admin
        }
    }), 200

@bp.route('/password/forgot/request', methods=['POST'])
def forgot_password_request():
    data = request.get_json()
    identifier = data.get('identifier')

    if not identifier:
        return jsonify({'error': 'Email or phone number is required'}), 400

    user = User.query.filter((User.email == identifier) | (User.phone_number == identifier)).first()
    if user:
        # TODO: Implement password reset token generation and sending
        pass

    return jsonify({'message': 'If your account exists, password reset instructions have been sent'}), 200

@bp.route('/password/reset/token', methods=['POST'])
def reset_password_token():
    data = request.get_json()
    token = data.get('token')
    new_password = data.get('new_password')

    if not token or not new_password:
        return jsonify({'error': 'Token and new password are required'}), 400

    # TODO: Implement token verification and password update
    return jsonify({'message': 'Password has been reset successfully'}), 200